<template>
  <div>
    <div class="main-content">
      <div class="page-title">草稿箱</div>

      <!-- 草稿统计 -->
      <div class="drafts-stats">
        <div class="stat-card">
          <div class="stat-title">草稿总数</div>
          <div class="stat-value">{{ totalDrafts }}</div>
        </div>

        <div class="stat-card">
          <div class="stat-title">今日新增</div>
          <div class="stat-value">{{ todayDrafts }}</div>
        </div>

        <div class="stat-card">
          <div class="stat-title">待完善</div>
          <div class="stat-value">{{ incompleteDrafts }}</div>
        </div>

        <div class="stat-card">
          <div class="stat-title">已保存</div>
          <div class="stat-value">{{ savedDrafts }}</div>
        </div>
      </div>

      <!-- 草稿箱 -->
      <div class="drafts-container">
        <div class="drafts-header">
          <div class="drafts-title">我的草稿</div>
          <div class="drafts-actions">
            <el-button type="primary" size="small" @click="createNewDraft">
              <i class="fa-solid fa-plus"></i> 新建草稿
            </el-button>
            <el-button type="text" size="small" @click="batchSelect">
              <i class="fa-solid fa-check-square"></i> 批量选择
            </el-button>
            <el-button type="text" size="small" @click="emptyTrash">
              <i class="fa-solid fa-trash"></i> 清空回收站
            </el-button>
          </div>
        </div>

        <div class="drafts-filter">
          <el-form>
            <el-form-item>
              <el-input
                  v-model="searchKeyword"
                  placeholder="搜索草稿标题"
                  class="search-input-77 mr-3"
              >
                <template #prefix>
                  <span>订单号</span>
                  <el-divider direction="vertical"></el-divider>
                </template>
              </el-input>
               <el-button class="screen-button" type="primary" @click="handleFilter">搜索</el-button>
            </el-form-item>
            <el-form-item>

            </el-form-item>

          </el-form>

          <el-select v-model="categoryFilter" placeholder="选择分类" size="small">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="category in categories" :key="category.id" :label="category.name"
                       :value="category.id"></el-option>
          </el-select>

          <el-select v-model="statusFilter" placeholder="选择状态" size="small">
            <el-option label="全部" value=""></el-option>
            <el-option label="待完善" value="incomplete"></el-option>
            <el-option label="已保存" value="saved"></el-option>
          </el-select>

          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
          ></el-date-picker>

          <el-button type="text" size="small" @click="resetFilters">重置</el-button>
        </div>

        <!-- 草稿列表 -->
        <div class="drafts-list">
          <!-- 修改前 -->
          <!-- <div class="draft-card" v-for="(draft, index) in filteredDrafts" :key="draft.id"> -->
          <!-- 修改后 -->
          <div class="draft-card" v-for="draft in filteredDrafts" :key="draft.id">
            <el-checkbox
                v-model="batchSelectMode"
                :checked="selectedDrafts.includes(draft.id)"
                @change="handleSelectDraft(draft.id)"
                class="batch-checkbox"
            ></el-checkbox>

            <div class="draft-cover">
              <img :src="draft.coverImage" alt="草稿封面">
              <div class="cover-overlay">
                <div class="preview-btn" @click="previewDraft(draft.id)">预览草稿</div>
              </div>
            </div>

            <div class="draft-info">
              <div class="draft-title">{{ draft.title }}</div>

              <div class="draft-tags">
                <div class="draft-tag" v-for="tag in draft.tags" :key="tag">{{ tag }}</div>
              </div>

              <div class="draft-meta">
                <div>{{ formatDate(draft.updatedAt) }}</div>
                <div class="draft-status"
                     :class="{'text-success': draft.status === 'saved', 'text-warning': draft.status === 'incomplete'}">
                  {{ draft.status === 'saved' ? '已保存' : '待完善' }}
                </div>
              </div>

              <div class="draft-actions">
                <el-button type="primary" size="mini" @click="editDraft(draft.id)">
                  <i class="fa-solid fa-edit"></i> 编辑
                </el-button>
                <el-dropdown trigger="click">
                  <el-button type="text" size="mini">
                    更多 <i class="fa-solid fa-angle-down el-icon--right"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="publishDraft(draft.id)">发布</el-dropdown-item>
                      <el-dropdown-item @click="copyDraft(draft.id)">复制</el-dropdown-item>
                      <el-dropdown-item @click="moveToTrash(draft.id)">移至回收站</el-dropdown-item>
                      <el-dropdown-item @click="viewHistory(draft.id)">查看历史</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 暂无草稿提示 -->
          <div v-if="filteredDrafts.length === 0" class="empty-drafts">
            <div class="empty-icon">
              <i class="fa-solid fa-file-text-o"></i>
            </div>
            <div class="empty-text">暂无草稿</div>
            <el-button type="primary" @click="createNewDraft">新建草稿</el-button>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="drafts.length"
          ></el-pagination>
        </div>
      </div>
    </div>
    <!-- 批量操作弹窗 -->
    <el-dialog :visible.sync="batchActionsVisible" title="批量操作">
      <div slot="content">
        <div class="batch-actions-list">
          <div class="batch-action-item" @click="batchPublish">
            <i class="fa-solid fa-paper-plane"></i> 发布选中草稿
          </div>
          <div class="batch-action-item" @click="batchCopy">
            <i class="fa-solid fa-copy"></i> 复制选中草稿
          </div>
          <div class="batch-action-item" @click="batchMoveToTrash">
            <i class="fa-solid fa-trash"></i> 移至回收站
          </div>
          <div class="batch-action-item" @click="batchChangeCategory">
            <i class="fa-solid fa-folder"></i> 更改分类
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchActionsVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog :visible.sync="deleteConfirmVisible" title="确认删除">
      <div slot="content">
        <p>确定要删除选中的草稿吗？</p>
        <p class="text-warning">删除后将无法恢复！</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteConfirmVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteDrafts">确认删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'; // 添加axios导入

export default {
  name: "DraftsView-view",
  components: {},
  props: {},
  data() {
    return {
      activeMenu: 'publish-drafts',
      drafts: [],
      categories: [
        {id: '1', name: '时尚穿搭'},
        {id: '2', name: '美妆个护'},
        {id: '3', name: '美食探店'},
        {id: '4', name: '旅行攻略'},
        {id: '5', name: '生活方式'},
        {id: '6', name: '健身运动'},
        {id: '7', name: '影视娱乐'}
      ],
      searchKeyword: '',
      categoryFilter: '',
      statusFilter: '',
      dateRange: '',
      currentPage: 1,
      pageSize: 10,
      batchSelectMode: false,
      selectedDrafts: [],
      batchActionsVisible: false,
      deleteConfirmVisible: false,
      totalDrafts: 0,
      todayDrafts: 0,
      incompleteDrafts: 0,
      savedDrafts: 0
    }
  },
  computed: {
    filteredDrafts() {
      let filtered = this.drafts;

      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        filtered = filtered.filter(draft =>
            draft.title.toLowerCase().includes(keyword) ||
            (draft.tags && draft.tags.some(tag => tag.toLowerCase().includes(keyword)))
        );
      }

      if (this.categoryFilter) {
        filtered = filtered.filter(draft => draft.categoryId === this.categoryFilter);
      }

      if (this.statusFilter) {
        filtered = filtered.filter(draft => draft.status === this.statusFilter);
      }

      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filtered = filtered.filter(draft => {
          const draftDate = new Date(draft.updatedAt);
          return draftDate >= startDate && draftDate <= endDate;
        });
      }

      return filtered;
    }
  },
  watch: {},
  created() {
  },
  mounted() {
    this.loadDrafts();
  },
  methods: {
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    loadDrafts() {
      // 模拟API请求获取草稿数据
      axios.get('/api/drafts').then(response => {
        this.drafts = response.data;
        this.updateStats();
      }).catch(() => { // 移除未使用的error参数
        this.$message.error('加载草稿失败');
      });
    },
    updateStats() {
      this.totalDrafts = this.drafts.length;
      this.todayDrafts = this.drafts.filter(draft => {
        const today = new Date();
        const draftDate = new Date(draft.createdAt);
        return draftDate.toDateString() === today.toDateString();
      }).length;
      this.incompleteDrafts = this.drafts.filter(draft => draft.status === 'incomplete').length;
      this.savedDrafts = this.drafts.filter(draft => draft.status === 'saved').length;
    },
    createNewDraft() {
      this.$router.push('/publish/create');
    },
    batchSelect() {
      this.batchSelectMode = !this.batchSelectMode;
      if (!this.batchSelectMode) {
        this.selectedDrafts = [];
      }
    },
    handleSelectDraft(draftId) {
      const index = this.selectedDrafts.indexOf(draftId);
      if (index === -1) {
        this.selectedDrafts.push(draftId);
      } else {
        this.selectedDrafts.splice(index, 1);
      }
    },
    emptyTrash() {
      this.$confirm('确定清空回收站吗？此操作不可恢复', '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete('/api/drafts/trash').then(() => {
          this.$message.success('回收站已清空');
          this.loadDrafts();
        });
      });
    },
    searchDrafts() {
      this.currentPage = 1;
    },
    resetFilters() {
      this.searchKeyword = '';
      this.categoryFilter = '';
      this.statusFilter = '';
      this.dateRange = '';
      this.currentPage = 1;
    },
    previewDraft(draftId) {
      window.open(`/preview/${draftId}`, '_blank');
    },
    editDraft(draftId) {
      this.$router.push(`/publish/edit/${draftId}`);
    },
    publishDraft(draftId) {
      this.$confirm('确定发布此草稿吗？', '提示').then(() => {
        axios.post(`/api/drafts/${draftId}/publish`).then(() => {
          this.$message.success('发布成功');
          this.loadDrafts();
        });
      });
    },
    copyDraft(draftId) {
      axios.post(`/api/drafts/${draftId}/copy`).then(() => {
        this.$message.success('复制成功');
        this.loadDrafts();
      });
    },
    moveToTrash(draftId) {
      this.$confirm('确定将此草稿移至回收站吗？', '提示').then(() => {
        axios.delete(`/api/drafts/${draftId}`).then(() => {
          this.$message.success('已移至回收站');
          this.loadDrafts();
        });
      });
    },
    viewHistory(draftId) {
      this.$router.push(`/publish/history/${draftId}`);
    },
    batchPublish() {
      if (this.selectedDrafts.length === 0) {
        this.$message.warning('请先选择草稿');
        return;
      }
      this.$confirm(`确定批量发布${this.selectedDrafts.length}篇草稿吗？`, '提示').then(() => {
        axios.post('/api/drafts/batch-publish', {ids: this.selectedDrafts}).then(() => {
          this.$message.success('批量发布成功');
          this.loadDrafts();
          this.batchActionsVisible = false;
        });
      });
    },
    batchCopy() {
      // 类似batchPublish的实现
    },
    batchMoveToTrash() {
      // 类似batchPublish的实现
    },
    batchChangeCategory() {
      // 实现批量修改分类
    },
    confirmDeleteDrafts() {
      // 确认删除选中的草稿
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  },
};
</script>
<style scoped lang="scss">
.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.drafts-stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.stat-card {
  /* 原有样式保留 */
  width: 24%;
  background-color: white;
  border-radius: 10px;
  padding: 50px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  font-weight: bolder;
  transition: all 0.3s ease; /* 添加过渡动画 */
  position: relative; /* 确保动画层级 */
   box-shadow: 0 10px 20px rgba(0, 0, 0, 0.03);
}

.stat-value {
  margin-left: 10px;
}

.stat-card:hover {
  transform: translateY(-10px); /* 上移10px */
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15); /* 增强投影 */
}


.stat-card:hover::after {
  width: 60%; /* 鼠标移入时显示线条 */
  left: 20%; /* 调整线条位置 */
}

/* 草稿箱相关样式 */
.drafts-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.drafts-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.drafts-actions {
  display: flex;
  gap: 10px;
}

.drafts-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.drafts-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.draft-card {
  border: 1px solid #EBEEF5;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.draft-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.draft-cover {
  height: 200px;
  background-color: #F5F7FA;
  position: relative;
}

.draft-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.draft-cover .cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.draft-card:hover .cover-overlay {
  opacity: 1;
}

.cover-overlay .preview-btn {
  background-color: white;
  color: var(--primary-color);
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
}

.draft-info {
  padding: 16px;
}

.draft-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.4;
  max-height: 2.8em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.draft-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: var(--gray-color);
  font-size: 12px;
  margin-bottom: 12px;
}

.draft-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.draft-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 12px;
}

.draft-tag {
  background-color: #F5F7FA;
  color: var(--gray-color);
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 批量操作弹窗 */
.batch-actions-dialog .el-dialog__content {
  padding: 20px;
}

.batch-actions-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.batch-action-item {
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.batch-action-item:hover {
  background-color: #F5F7FA;
}

</style>
